package com.funtest.shard.database.policy;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @Author: flathead
 * @Date: 2021/5/3 10:52
 */
@Slf4j
public class OrderCheckShardingTableAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<Long> shardingValue) {
        StringBuilder buf = new StringBuilder();
        Long orderId = shardingValue.getValue();
        String orderIdStr = orderId.toString();
//        String orderIdSuffix = orderIdStr.substring(orderIdStr.length() - 2);
//        String logicTableName = shardingValue.getLogicTableName();
//        buf.append(logicTableName).append("_").append(orderIdSuffix);
//        if(tableNames.contains(buf.toString())) {
//            return buf.toString();
//        } else {
//            String errMsg = String.format("取模精确分片策略：没找到与分片键匹配的表名! %s : %s = %s", shardingValue.getLogicTableName(), shardingValue.getColumnName(), shardingValue.getValue());
//            log.info(errMsg);
//            throw new UnsupportedOperationException(errMsg);
//        }
//        if(tableNames.contains(orderId%2)) {
//            return buf.toString();
//        } else {
//            String errMsg = String.format("取模精确分片策略：没找到与分片键匹配的表名! %s : %s = %s", shardingValue.getLogicTableName(), shardingValue.getColumnName(), shardingValue.getValue());
//            log.info(errMsg);
//            throw new UnsupportedOperationException(errMsg);
//        }
        for (String tableName:tableNames){
            if (tableName.endsWith(String.valueOf(orderId%2))){
                return tableName;
            }
        }
        throw new UnsupportedOperationException("xxxx");
    }

}
